{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Fi_y0ooAzjjy"
   },
   "source": [
    "# AI Market & Startup Trend Agent"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "M18iBcPYzl9d"
   },
   "source": [
    "* An AI-powered agent that analyzes current market and startup trends using real-time news, web search, and multi-agent collaboration.\n",
    "* The agent collects recent articles, summarizes key insights, and identifies emerging opportunities for entrepreneurs and investors.\n",
    "* Features include automated news gathering, trend summarization, and actionable reports on startup opportunities in any area of interest."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "SfsvzoD_3JtE"
   },
   "source": [
    "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/ai_market_startup_trend_agent.ipynb)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6par7OlW0KVF"
   },
   "source": [
    "# Dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "oJA89ujM0OSd"
   },
   "outputs": [],
   "source": [
    "!pip install praisonai streamlit duckduckgo-search \"newspaper3k[lxml]\" anthropic lxml_html_clean"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bK4r7sQ_0hz0"
   },
   "source": [
    "# Setup Key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "9UViB-oJ0izp",
    "outputId": "f1db522f-5e30-4f14-8fc1-5c5b814a10c7"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ Anthropic API key configured!\n"
     ]
    }
   ],
   "source": [
    "# Setup Key\n",
    "import os\n",
    "\n",
    "# Set your Anthropic API key\n",
    "anthropic_key = \"your_anthropic_key_here\"  # Get from https://console.anthropic.com\n",
    "\n",
    "# Set environment variable\n",
    "os.environ[\"ANTHROPIC_API_KEY\"] = anthropic_key\n",
    "\n",
    "print(\"✅ Anthropic API key configured!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "TX6AKmiE0sK3"
   },
   "source": [
    "# Tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "id": "afU4kjcz0tCk"
   },
   "outputs": [],
   "source": [
    "# Custom News & Trend Analysis Tools\n",
    "\n",
    "from duckduckgo_search import DDGS\n",
    "from newspaper import Article\n",
    "from typing import List, Dict, Any\n",
    "\n",
    "class NewsSearchTool:\n",
    "    def __init__(self, max_results: int = 5):\n",
    "        self.max_results = max_results\n",
    "\n",
    "    def search_news(self, topic: str) -> List[Dict[str, Any]]:\n",
    "        \"\"\"Search for recent news articles on a topic using DuckDuckGo.\"\"\"\n",
    "        results = []\n",
    "        with DDGS() as ddgs:\n",
    "            for r in ddgs.news(topic, max_results=self.max_results):\n",
    "                results.append({\n",
    "                    \"title\": r.get(\"title\"),\n",
    "                    \"url\": r.get(\"url\"),\n",
    "                    \"date\": r.get(\"date\"),\n",
    "                    \"body\": r.get(\"body\")\n",
    "                })\n",
    "        return results\n",
    "\n",
    "class ArticleSummaryTool:\n",
    "    def summarize_articles(self, articles: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n",
    "        \"\"\"Summarize the content of news articles using Newspaper3k.\"\"\"\n",
    "        summaries = []\n",
    "        for article in articles:\n",
    "            try:\n",
    "                a = Article(article[\"url\"])\n",
    "                a.download()\n",
    "                a.parse()\n",
    "                a.nlp()\n",
    "                summaries.append({\n",
    "                    \"title\": article[\"title\"],\n",
    "                    \"summary\": a.summary,\n",
    "                    \"url\": article[\"url\"]\n",
    "                })\n",
    "            except Exception as e:\n",
    "                summaries.append({\n",
    "                    \"title\": article[\"title\"],\n",
    "                    \"summary\": f\"Error summarizing article: {str(e)}\",\n",
    "                    \"url\": article[\"url\"]\n",
    "                })\n",
    "        return summaries\n",
    "\n",
    "class TrendInsightTool:\n",
    "    def extract_trends(self, summaries: List[Dict[str, Any]]) -> Dict[str, Any]:\n",
    "        \"\"\"Extract and aggregate trend insights from article summaries.\"\"\"\n",
    "        all_text = \" \".join([s[\"summary\"] for s in summaries if \"summary\" in s])\n",
    "        # For demo: just return the combined summaries\n",
    "        # In production: use LLM to extract trends and opportunities\n",
    "        return {\n",
    "            \"trend_report\": all_text[:2000] + (\"...\" if len(all_text) > 2000 else \"\")\n",
    "        }"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "CVCoaGTO0-Ue"
   },
   "source": [
    "# YAML Prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "6xu0NeHy0_ZV",
    "outputId": "2d85f20a-8af4-49a4-ec76-9db4102e0d51"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ YAML Prompt configured!\n"
     ]
    }
   ],
   "source": [
    "# YAML Prompt\n",
    "yaml_prompt = \"\"\"\n",
    "name: \"AI Market & Startup Trend Agent\"\n",
    "description: \"Expert market analyst that gathers, summarizes, and analyzes startup and market trends from real-time news sources\"\n",
    "instructions:\n",
    "  - \"You are an expert market and startup trend analyst\"\n",
    "  - \"Search for the latest news and articles on the user's topic of interest\"\n",
    "  - \"Summarize the key points and insights from each article\"\n",
    "  - \"Aggregate the summaries to identify emerging trends and startup opportunities\"\n",
    "  - \"Present findings in a clear, actionable report for entrepreneurs and investors\"\n",
    "  - \"Cite sources and provide links to original articles\"\n",
    "  - \"Highlight any patterns, risks, or opportunities you discover\"\n",
    "  - \"Use bullet points and markdown formatting for clarity\"\n",
    "\n",
    "tools:\n",
    "  - name: \"NewsSearchTool\"\n",
    "    description: \"Searches for recent news articles on a given topic using DuckDuckGo\"\n",
    "  - name: \"ArticleSummaryTool\"\n",
    "    description: \"Summarizes the content of news articles using Newspaper3k\"\n",
    "  - name: \"TrendInsightTool\"\n",
    "    description: \"Extracts and aggregates trend insights from article summaries\"\n",
    "\n",
    "output_format:\n",
    "  - \"Provide a trend analysis report with actionable insights\"\n",
    "  - \"Include a list of summarized articles with links\"\n",
    "  - \"Highlight key opportunities and risks\"\n",
    "  - \"Use clear, structured formatting with sections for news, summaries, and trends\"\n",
    "\n",
    "temperature: 0.4\n",
    "max_tokens: 3500\n",
    "model: \"claude-3-5-sonnet\"\n",
    "\"\"\"\n",
    "\n",
    "print(\"✅ YAML Prompt configured!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "MaX_eyRB1jtF"
   },
   "source": [
    "# Main"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "collapsed": true,
    "id": "fmMkG5hR1lS7",
    "outputId": "0833615c-c919-406e-9646-9cd8d74f78ed"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[nltk_data] Error loading tokenizers/punkt: Package 'tokenizers/punkt'\n",
      "[nltk_data]     not found in index\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "📈 AI Market & Startup Trend Agent\n",
      "Analyze current market and startup trends using real-time news and AI summarization!\n",
      "\n",
      "Enter the area of interest for your Startup or Market Trend Analysis: Chennai\n",
      "\n",
      "🔍 Searching for recent news on: Chennai\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipython-input-6-1293765785.py:14: RuntimeWarning: This package (`duckduckgo_search`) has been renamed to `ddgs`! Use `pip install ddgs` instead.\n",
      "  with DDGS() as ddgs:\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ Found 5 articles. Summarizing...\n",
      "\n",
      "📰 Article Summaries:\n",
      "1. Chennai woman breaks down in front of traffic cop, shares the reason in viral post\n",
      "   \n",
      "   [Read more](https://www.msn.com/en-in/news/other/chennai-woman-breaks-down-in-front-of-traffic-cop-shares-the-reason-in-viral-post/ar-AA1IalYh)\n",
      "\n",
      "2. Chennai founder breaks down in front of traffic police after his unexpected question: 'And that's when the tears came'\n",
      "   \n",
      "   [Read more](https://www.msn.com/en-in/news/India/chennai-founder-breaks-down-in-front-of-traffic-police-after-his-unexpected-question-and-that-s-when-the-tears-came/ar-AA1Ia579)\n",
      "\n",
      "3. Explore India's coastal flavours at this Chennai food fest\n",
      "   \n",
      "   [Read more](https://www.msn.com/en-in/foodanddrink/other/explore-indias-coastal-flavours-at-this-chennai-food-fest/ar-AA1Iax3e)\n",
      "\n",
      "4. Chennai weather update: Expect patchy rain and a warm summer day\n",
      "   \n",
      "   [Read more](https://www.msn.com/en-in/news/india/chennai-weather-update-expect-patchy-rain-and-a-warm-summer-day/ar-AA1I9ECV)\n",
      "\n",
      "5. Chennai Power Outage Alert: Check Areas That Will Face Supply Disruption On July 8 For Maintenance Work\n",
      "   \n",
      "   [Read more](https://www.msn.com/en-in/autos/photos/chennai-power-outage-alert-check-areas-that-will-face-supply-disruption-on-july-8-for-maintenance-work/ar-AA1I9KIg)\n",
      "\n",
      "📊 Analyzing trends and opportunities...\n",
      "\n",
      "=== Trend Analysis Report ===\n",
      "    \n",
      "\n",
      "🧪 Sample Topics for Testing\n",
      "1. AI in healthcare\n",
      "2. Sustainable energy startups\n",
      "3. Fintech innovation\n",
      "4. Remote work technology\n",
      "5. Climate tech investments\n",
      "\n",
      "==================================================\n",
      "📈 Powered by AI Market & Startup Trend Agent | Built with PraisonAI\n"
     ]
    }
   ],
   "source": [
    "# Main Application (Google Colab Version)\n",
    "import os\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\", category=ImportWarning)\n",
    "\n",
    "# Download all necessary NLTK data for newspaper3k\n",
    "import nltk\n",
    "nltk.download('tokenizers/punkt')\n",
    "nltk.download('averaged_perceptron_tagger', quiet=True)\n",
    "nltk.download('maxent_ne_chunker', quiet=True)\n",
    "nltk.download('words', quiet=True)\n",
    "\n",
    "# Initialize tools\n",
    "news_tool = NewsSearchTool()\n",
    "summary_tool = ArticleSummaryTool()\n",
    "trend_tool = TrendInsightTool()\n",
    "\n",
    "print(\"📈 AI Market & Startup Trend Agent\")\n",
    "print(\"Analyze current market and startup trends using real-time news and AI summarization!\")\n",
    "\n",
    "# User input\n",
    "topic = input(\"\\nEnter the area of interest for your Startup or Market Trend Analysis: \").strip()\n",
    "\n",
    "if topic:\n",
    "    print(f\"\\n🔍 Searching for recent news on: {topic}\")\n",
    "    articles = news_tool.search_news(topic)\n",
    "    if articles:\n",
    "        print(f\"✅ Found {len(articles)} articles. Summarizing...\")\n",
    "        summaries = summary_tool.summarize_articles(articles)\n",
    "        print(\"\\n📰 Article Summaries:\")\n",
    "        for i, s in enumerate(summaries, 1):\n",
    "            print(f\"{i}. {s['title']}\")\n",
    "            print(f\"   {s['summary']}\")\n",
    "            print(f\"   [Read more]({s['url']})\\n\")\n",
    "\n",
    "        print(\"📊 Analyzing trends and opportunities...\")\n",
    "        trend_report = trend_tool.extract_trends(summaries)\n",
    "        print(\"\\n=== Trend Analysis Report ===\")\n",
    "        print(trend_report[\"trend_report\"])\n",
    "    else:\n",
    "        print(\"❌ No news articles found for this topic.\")\n",
    "else:\n",
    "    print(\"❌ No topic entered. Please provide a topic to analyze.\")\n",
    "\n",
    "# Sample topics for testing\n",
    "print(\"\\n🧪 Sample Topics for Testing\")\n",
    "sample_topics = [\n",
    "    \"AI in healthcare\",\n",
    "    \"Sustainable energy startups\",\n",
    "    \"Fintech innovation\",\n",
    "    \"Remote work technology\",\n",
    "    \"Climate tech investments\"\n",
    "]\n",
    "for i, t in enumerate(sample_topics, 1):\n",
    "    print(f\"{i}. {t}\")\n",
    "\n",
    "# Footer\n",
    "print(\"\\n\" + \"=\"*50)\n",
    "print(\"📈 Powered by AI Market & Startup Trend Agent | Built with PraisonAI\")"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
